package pers.hll.aigc4chat.server.component;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import pers.hll.aigc4chat.base.exception.BizException;
import pers.hll.aigc4chat.base.util.XmlUtil;
import pers.hll.aigc4chat.base.xml.BaiduConfig;
import pers.hll.aigc4chat.base.xml.OllamaConfig;
import pers.hll.aigc4chat.model.ollama.constant.ModelName;
import pers.lys.aigc4chat.model.baidu.BaiduApi;
import java.io.IOException;

/**
 * 启动后检查所有的配置文件是否存在 没有的话将必要的默认值写入配置文件
 *
 * @author hll
 * @since 2024/05/06
 */
@Slf4j
@Component
public class XmlConfigInitRunner implements CommandLineRunner {

    @Override  
    public void run(String... args) {  
        initBaiduConfig();
        initOllamaConfig();
        initProxyConfig();
    }

    private void initBaiduConfig() {
        BaiduConfig baiduConfig = XmlUtil.readXmlConfig(BaiduConfig.class);
        // 第一次初始化
        if (StringUtils.isEmpty(baiduConfig.getChatBaseUrl()) || StringUtils.isEmpty(baiduConfig.getAccessTokenUrl())) {
            baiduConfig.setChatBaseUrl("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/");
            baiduConfig.setAccessTokenUrl("https://aip.baidubce.com/oauth/2.0/token");
            try {
                XmlUtil.writeXmlConfig(baiduConfig);
                return;
            } catch (IOException e) {
                log.error("初始化百度配置文件失败: ", e);
                throw BizException.of("初始化百度配置文件失败: ", e);
            }
        }
        BaiduApi.refreshAccessToken();
    }

    private void initOllamaConfig() {
        OllamaConfig ollamaConfig = XmlUtil.readXmlConfig(OllamaConfig.class);
        if (ollamaConfig == null ||
                ObjectUtils.anyNull(ollamaConfig.getHost(), ollamaConfig.getPort(), ollamaConfig.getProtocol())) {
            try {
                XmlUtil.writeXmlConfig(OllamaConfig.builder()
                        .protocol("http")
                        .host("localhost")
                        .port(11434)
                        .build());
            } catch (IOException e) {
                log.error("初始化ollama配置文件失败", e);
            }
        }
    }

    private void initProxyConfig() {
        // do nothing
    }

}  